package cn.dlc.com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Arrays;

/**
 * @Author: dlc
 * @Date: 2021/11/24 - 14:15
 */
@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JdbcClientDetailsService jdbcClientDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    /**
     * 令牌管理，
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // 整合数据库的配置
        tokenServices.setClientDetailsService(jdbcClientDetailsService);
        // 是否刷新令牌
        tokenServices.setSupportRefreshToken(true);
        // 存储令牌策略
         tokenServices.setTokenStore(tokenStore);

         // 令牌增强
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        tokenServices.setTokenEnhancer(enhancerChain);

        // 令牌有效时间2小时
        tokenServices.setAccessTokenValiditySeconds(2*60*60);
        // 令牌有效时间3天
        tokenServices.setRefreshTokenValiditySeconds(3*24*60*60);
        return tokenServices;
    }


    /**
     * 配置客户端信息，注册的客户端可以从这里关联到数据库或者直接写死在这里
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 整合数据库的配置
        clients.withClientDetails(jdbcClientDetailsService);
    }

    /**
     * 用来配置令牌的访问端点和令牌的服务
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints
                // 认证管理器（授权模式为密码模式的时候用他）
                .authenticationManager(authenticationManager)
                // 授权码服务(授权码服务才用他)
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务
                .tokenServices(tokenServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * 配置令牌端点的安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 下面配置的这两个端口是可以允许所有人访问的，
        // 一个用来获取令牌，一个用来校验令牌
        security
                // oauth/token_key:申请令牌的端点
                .tokenKeyAccess("permitAll()")
                // oauth/token_check端点公开：校验令牌的端点
                 .checkTokenAccess("permitAll()")
                // 表单认证
                .allowFormAuthenticationForClients();
    }

}
